import React from 'react';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';
import { Link } from 'react-router-dom';
import { Tools, Icon, TextareaItem, Picker } from 'weaver-mobile';
import { ListAdvanced, SearchAdvanced, TabPage, RouteLayout ,Share} from 'weaver-mobile-page';
import { forwardViewForm,forwardViewPage } from '../../util/common';
import { withRouter, Route } from 'react-router-dom';
import TagManage from "../follow/tagManage";
import TagEdit from "../follow/tagEdit";
// import { getTree } from 'mobile4mobx/workflow/apis/attention';
const getLabel = Tools.getLabel;
const Item = TabPage.Item;
const ButtonGroup = RouteLayout.ButtonGroup;

@inject('attentionStore','followStore')
@withRouter
@observer
export default class App extends React.Component {

    componentWillMount() {
        const { attentionStore,location={} } = this.props;
        const { setState,listAd_All,init,tabs,nowTab,getTree } = attentionStore;
        const {pathname=""}=location;
        // getTree();
        let pathid = pathname.split("/")[2];
        if(pathid.includes("?"))
            pathid=pathid.substr(0,pathid.indexOf("?"));
        setState({listAd_All:new ListAdvanced.Store({ route: pathname, id: pathid })})
    }
    
    componentDidMount() {
        const { attentionStore,followStore } = this.props;
        const { getTreeCount, nowTab, nowListAd,tabs,setState } = attentionStore;
        const {listViewStore} = nowListAd
        let pathidArr  = (window.location.hash.split('/'))
        let pathid =  pathidArr[2].includes("?") ? pathidArr[2].substr(0, pathidArr[2].indexOf("?")) : pathidArr[2];
        // listViewStore.clearData()
        nowListAd.getData({ url: '/api/workflow/requestAttention/getSessionkey', method: "POST", params: { tabKey: pathid, _ec_device: true } });
        setState({queryAdress:this.props.location.pathname}) 
    }

    componentWillUpdate(nextProps) {
        const { isShowTotal: new_isShowTotal, setState, listAd_All, nowListAd} = nextProps.attentionStore;
        const { listViewStore } = listAd_All;
        if (new_isShowTotal && listViewStore.data.length > 0) {
            setState({ isShowTotal: false });
        }  
    }

    onSearch = (status = {}) => {
        const { nowListAd, nowTab, leftTree_params, getTreeCount,tabs } = this.props.attentionStore;
        const { searchAdvancedStore, listViewStore, searchParams } = nowListAd;
        // 搜索框等搜索数据
        let params = { ...searchParams };
        // 获取高级搜索参数
        if (searchAdvancedStore) {
            const { formParams } = searchAdvancedStore.form;
            params = { ...formParams, ...leftTree_params };
        }
        // 清除列表数据
        listViewStore.clearData();
        if (!status.notClearSelectedRowKeys) {//清空列表已选中数据
            listViewStore.setState({ selectedRowKeys: [] })
        }
        // 带参数请求列表数据
        let pathidArr  = (window.location.hash.split('/'))
        let pathid =  pathidArr[2].includes("?") ? pathidArr[2].substr(0, pathidArr[2].indexOf("?")) : pathidArr[2];
        nowListAd.getData({ url: '/api/workflow/requestAttention/getSessionkey', method: "POST", params: { ...params, tabKey:pathid, ismobile: 1, _ec_device: true } });
    }


    onLeftTreeChange = (domid, name, valueArray) => {
        const { nowListAd, setState, getTreeCount } = this.props.attentionStore;
        const fileds = {};
        if (/^wf_-?\d+/.test(domid)) {
            fileds.workflowId = domid.replace(/^wf_/, '');
        }
        if (/^type_-?\d+/.test(domid)) {
            fileds.workflowType = domid.replace(/^type_/, '');
        }
        if (domid === '') {
            fileds.workflowType = "";
            fileds.workflowId = "";
        }

        setState({ leftTree_params: fileds, leftTreeValueArray: valueArray })
        // 同步树选中项到高级搜索的 from 中
        if (!nowListAd.searchAdvancedStore) {
            nowListAd.setState({
                searchAdvancedStore: new SearchAdvanced.Store({
                    route: nowListAd.path,
                    id: 'SearchAdvanced',
                }),
            });
            nowListAd.searchAdvancedStore.getData({
                url: '/api/workflow/requestAttention/getCondition',
                method: 'GET',
                params: { ismobile: 1, _ec_device: true }
            }).then((form) => {
                if (nowListAd.searchParams.requestname) {
                    fileds.requestname = { value: nowListAd.searchParams.requestname };
                    form.updateFields(fileds);
                    this.onSearch();
                }
            });
        } else {
            nowListAd.searchAdvancedStore.form.updateFields(fileds);
            this.onSearch();
        }

    }

    onRowClick = (data) => {
        const { location = {},attentionStore } = this.props;
        const { pathname = "" } = location;
        const { showCheck,nowListAd } = attentionStore;
        const { listViewStore } = nowListAd;
        let { selectedRowKeys = [] } = listViewStore;
        if (showCheck) {
            if (selectedRowKeys.includes(data.randomFieldId)) {
                selectedRowKeys.splice(selectedRowKeys.indexOf(data.randomFieldId), 1)
                listViewStore.setState({ selectedRowKeys })
            } else {
                listViewStore.setState({ selectedRowKeys: [...selectedRowKeys, data.randomFieldId] })
            };
        } else {
            //跳到表单页面
            if (data.appurlspan) {
                let timestamp = new Date().getTime();
                let url = data.appurlspan;
                if(url.includes("?")){
                    url = `${url}&timestamp=${timestamp}`
                }else{
                    url = `${url}?timestamp=${timestamp}`
                }
                forwardViewPage(url, this.forwadCallback)
            } else{
                let urlParams = {
                    requestid: data.requestid,
                    timestamp: Date.parse(new Date()),
                }
                if(data.openByDefaultBrowserspan == 1){
                    urlParams.openByDefaultBrowser = data.openByDefaultBrowserspan;
                }
                if(data.issup == 1){
                    urlParams.urger=1;
                }
                forwardViewForm(  urlParams,this.forwadCallback );
            }
        }
    }

    batchFollow = () => {
        const { loadPhrasesDatas, nowListAd,layout ,bottomBth,setShareMsgInfo, setState} = this.props.attentionStore;
        const { listViewStore } = nowListAd;
        const { selectedRowKeys = [] } = listViewStore;
        const {location={}}=this.props;
        const {pathname=""}=location;
        if (selectedRowKeys.length > 0) {
            if(bottomBth==getLabel('6011','转发')){
                this.props.history.push({
                    pathname:'/attention/flowAll/share',
                    state:{requestids:selectedRowKeys.join(','),
                    addressBack:this.props.location.pathname,
                    mode:'forword'
                    }  
                  })
                  setShareMsgInfo()
            }
            else{
                setState({fatherPage : pathname});
                const {attentionStore} =this.props;
                const nowStore=attentionStore.nowListAd.route;
                this.props.history.push({
                    pathname:nowStore+'/follow',
                    state:{requestids:selectedRowKeys.join(','),
                    addressBack:this.props.location.pathname,
                    mode:'batch'
                    }  
                    
                  })
            } 
            localStorage.setItem('addressBack',this.props.location.pathname)
            localStorage.setItem('selectedFollowKeys',selectedRowKeys.join(','))
            
        }
        this.onSearch()
    }
    getSwipeActionProps =() =>({
        right: [
          {
            text: getLabel('25436', '关注'),
            onPress: (data) => {
              const {location={}}=this.props;
              const {pathname=""}=location;
              const { loadPhrasesDatas, nowListAd,layout,setState } = this.props.attentionStore;
              setState({fatherPage : pathname});
              const {attentionStore} =this.props;
              const nowStore=attentionStore.nowListAd.route;
              this.props.history.push({
                pathname:nowStore+'/follow',
                state:{requestids:data.requestid,
                       mode:'single'
                }
              })
            },
            className: `swipeFollow`,
            style:{width:"100px"},
          }
        ],
    })
    render() {
        const { nowListAd, showCheck, nowTab, tabs, leftTreeValueArray, flowCounts, needRemark, isShowTotal,layout ,bottomBth} = this.props.attentionStore;
        const { listViewStore } = nowListAd;
        const { selectedRowKeys = [] } = listViewStore;
        const extraPrompt = (flowCounts > 0 && isShowTotal&&nowTab===0) ? (<div style={{ textAlign: 'center', lineHeight: '30px', background: '#DFF1FF', color: '#55B1F9' }}>{getLabel(19661, "共有") + flowCounts + getLabel(18256, "条")}</div>) : null;
        const Highlight = nowListAd.islight;
        const searchPath = `${nowListAd.path}/SearchAdvanced`;
        const color = Highlight ? '#55B1F9' : '';
        let pathidArr  = (window.location.hash.split('/'))
        let pathid =  pathidArr[2].includes("?") ? pathidArr[2].substr(0, pathidArr[2].indexOf("?")) : pathidArr[2];
        return (
            <div>
                <ListAdvanced
                    store={nowListAd}
                    hasAdvanceSerach
                    extraPrompt={!showCheck ? extraPrompt : null}
                    rowKey="randomFieldId"
                    searchKey="requestname"
                    treeKey="domid"
                    dataFetchOptions={{
                        url: '/api/workflow/requestAttention/getSessionkey',
                        method: "POST",
                        params: {
                            tabKey: nowTab,
                            ismobile: 1,
                            _ec_device: true
                        }
                    }}
                    conditionFetchOptions={{
                        url: '/api/workflow/requestAttention/getCondition',
                        method: 'GET',
                        params: {
                            ismobile: 1,
                            _ec_device: true
                        }
                    }}
                    leftTreeFetchOptions={{
                        url: pathid?'/api/workflow/requestAttention/getTree?tabKey='+pathid:'/api/workflow/requestAttention/getTree',
                        method: 'POST',
                    }}
                    searchBarProps={{
                        showSelectButton: true,
                        selectText: getLabel(63, '类型'),
                        onSelectButtonClick: () => {},
                        placeholder: getLabel(391119, '请输入流程标题'),
                        extraButton: (tabs && tabs.length > 1) ? null : [
                            {
                                key: 'advanced', show: <Link to={searchPath}>
                                    <Icon
                                        type={`filter-o${Highlight ? '-hot' : ''}`}
                                        style={{ color }}
                                    />
                                </Link>
                            }]
                    }}
                    leftTreeBrowserProps={{
                        searchBarProps: {
                            placeholder: 'Search',
                            valueArray: toJS(leftTreeValueArray)
                        },
                    }}
                    showCheck={showCheck}
                    buttonGroupData={[{
                        key: 'submit',
                        text: bottomBth,
                        onClick: this.batchFollow,
                        className: selectedRowKeys.length > 0 ? 'wf-attention-btn-primary' : "wf-supervised-btn-disabled"
                    }]}
                    onSearch={this.onSearch}
                    onLeftTreeChange={this.onLeftTreeChange}
                    onRowClick={this.onRowClick}
                    withSwipeAction={!showCheck}
                    swipeActionProps={this.getSwipeActionProps()}
                    onHideCheck={() => {
                        const { setState,nowListAd } = this.props.attentionStore;
                        const { listViewStore } = nowListAd;
                        listViewStore.setState({ selectedRowKeys: [] })
                        setState({ showCheck: false, remark: "" });
                    }}
                />
                {needRemark && this.getRemark()}
            </div>
        )
    }
  
    getRemark = () => {
        const { setState, phrasesDatas, remark, doSupervise, nowListAd } = this.props.attentionStore;
        const { listViewStore } = nowListAd;
        const { selectedRowKeys } = listViewStore;
        const buttonGroup = [
            {
                key: 'reset',
                text: getLabel(201, '取消'),
                onClick: () => {
                    setState({ needRemark: false});
                },
            },
            {
                key: 'submit',
                text: getLabel(84561, "批量督办") + `（${selectedRowKeys.length}）`,
                onClick: () => {
                    //判断是否选择流程
                    const { nowListAd } = this.props.attentionStore;
                    const { listViewStore } = nowListAd;
                    const { selectedRowKeys = [] } = listViewStore;
                    let requestids = "";
                    if (selectedRowKeys.length > 0) {
                        requestids = toJS(selectedRowKeys).join(",");
                    }
                    doSupervise({ requestids: requestids, remark });
                },
                type: 'primary',
            },
        ];
        return (
            <div className="wf-signView-panel">
                <div
                    className="wf-signView-panel-mask"
                />
                <div className="wf-signView-panel-content">
                    <div className="sign-panel-title">
                        {this.getPhraseCom(phrasesDatas, setState, remark)}
                    </div>
                    <div style={{ marginBottom: 60 }} className="sign-panel-main">
                        {this.getRemarkEditor(setState, remark)}
                    </div>
                </div>
                <div className="sign-panel-bottom">
                    <ButtonGroup data={buttonGroup} />
                </div>

            </div>
        );
    }

    getRemarkEditor(setState, remark) {
        const modules = { toolbar: false };
        return (
            <TextareaItem
                value={remark}
                modules={modules}
                placeholder={getLabel(391154, '请输入签字意见')}
                onChange={v => {
                    setState({ remark: v })
                }}
                rows={4}
            />
        );
    }

    //常用批示语组件
    getPhraseCom(phraseInfo = [], setState, remark) {
        let menuData = [];
        phraseInfo.map((item, index) => {
            const { desc = '', short = '' } = item;
            menuData.push({ value: this.convertSpecialChar(desc) + "_wf_desc" + index, label: short });
        });
        return (
            <Picker data={menuData} cols={1} onOk={v => {
                if (v[0].includes("_wf_desc")) {
                    v[0] = v[0].slice(0, v.indexOf("_wf_desc") - ("_wf_desc").length)
                }
                remark = `${remark}${v}`;
                setState({ remark });
            }}>
                <div className={'sign-phrase-title'}>
                    <span className={'span-title'}>{getLabel(391155, "常用批示语")}</span>
                    <Icon type="down" />
                </div>
            </Picker>
        );
    }

    convertSpecialChar = (str) => {
        str = str.toString();
        str = str.replace(/<br>/ig, "\n");
        str = str.replace(/&nbsp;/ig, " ");
        str = str.replace(/&lt;/ig, "<");
        str = str.replace(/&gt;/ig, ">");
        str = str.replace(/&quot;/ig, "\"");
        str = str.replace(/&amp;/ig, "&");
        let reTag = /<(?:.|\s)*?>/g;
        return str.replace(reTag, "");
    }



}